const cart = {
  state: {
    cart: JSON.parse(uni.getStorageSync('cart') || '[]')
  },
  mutations: {
    addToCart(state, item) {
      if(state.cart.every(value => value.goods_id !== item.goods_id)) {
        state.cart.push(item)
      }
      else {
        state.cart.find(value => value.goods_id === item.goods_id).goods_count++
      }
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    updateSelect(state, item) {
      const obj = state.cart.find(value => {
        return value.goods_id === item.goods_id
      })
      obj.goods_state = !obj.goods_state
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    updateCount(state, obj) {
      const o = state.cart.find(value => {
        return value.goods_id === obj.item.goods_id
      })
      o.goods_count = o.goods_count + obj.count
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    delToCart(state, item) {
      state.cart = state.cart.filter(value => {
        return value.goods_id !== item.goods_id
      })
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    selectAllOrAgainst: (state, mark) => {
      state.cart.forEach(value => value.goods_state = mark)
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    }
  },
  actions: {
    addToCart(context, item) {
      context.commit('addToCart', item)
    },
    updateSelect(context, item) {
      context.commit('updateSelect', item)
    },
    updateCount(context, obj) {
      context.commit('updateCount', obj)
    },
    delToCart(context, item) {
      context.commit('delToCart', item)
    },
    selectAllOrAgainst: (context, mark) => context.commit('selectAllOrAgainst', mark)
  },
  getters: {
    info(state) {
      return state.cart.length
    },
    selectedQuantity: state => state.cart.reduce((prev, curr) => curr.goods_state ? prev + curr.goods_count : prev, 0),
    selectedPrice: state => state.cart.reduce((prev, curr) => curr.goods_state ? prev + curr.goods_count * curr.goods_price : prev, 0),
    isSelectAll: state => state.cart.every(value => value.goods_state)
  }
}

export default cart